package com.aruio.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 通用监听器 (适用于数据量少的情况)
 * @Date 2024/8/30 14:22
 * @Created by 10574
 */
@Slf4j
public class CommonListener<T> extends AnalysisEventListener<T> {
    private final List<T> data;
    private final Class<T> clazz;
    private final Field[] fields;
    // 是否校验
    private boolean validateSwitch = true;

    public CommonListener(Class<T> clazz) {
        this.clazz = clazz;
        this.fields = clazz.getDeclaredFields();
        this.data = new ArrayList<>();
    }

    @Override
    public void invoke(T row, AnalysisContext context) {
        data.add(row);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
            if (validateSwitch) {
                ExcelUtils.validateExcelTemplate(headMap, clazz, fields);
                log.info("excel表校验成功!!!");
            }
    }

    /**
     * 关闭excel表头验证
     */
    public void offValidate() {
        validateSwitch = false;
    }

    public List<T> getData() {
        return data;
    }
}
